<template>
  <el-card v-loading="$loadingPlugin.getCalculate" class="card">
    <div slot="header">
      <span>这次的商品信息</span>
    </div>
    <el-form inline :model="form">
      <el-form-item label="商品分类：" prop="gTypeId">
        <el-select
          v-model="form.gtId"
          placeholder="请选择商品分类"
          :disabled="isFirstDepositOrder"
          @change="goodTypeChange"
        >
          <el-option
            v-for="item in goodTypeList"
            :key="item.value"
            :label="item.gtName"
            :value="item.gtId"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-show="!isFirstDepositOrder" label="商品选择：" prop="goods">
        <el-select
          v-model="form.goodsId"
          placeholder="请选择商品选择"
          @change="goodsChange"
        >
          <el-option
            v-for="item in goodsList"
            :key="item.value"
            :label="item.goodsName"
            :value="item.goodsId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-if="!isFirstDepositOrder"
          type="primary"
          :loading="$loadingPlugin.onAdd"
          :disabled="readOnly"
          @click="onAdd(1)"
        >添加</el-button>
      </el-form-item>

      <!-- <el-table class="goods-table" :data="commodityData" :show-summary="true" :summary-method="getSummaries">
        <el-table-column prop="goodsName" label="商品名称" />
        <el-table-column prop="gprince" label="市价">
          <template slot-scope="scope">
            <span :class="scope.row.definePrice?'line-throuht':''">{{ scope.row.gprince }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="definePrice" label="特价" />
        <el-table-column prop="gcount" label="数量">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.gcount"
              class="purchaseQuantity"
              :controls="false"
              :min="1"
              :max="100"
              label=""
              @blur="gcountblurInput(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="gprefPrice" label="优惠" />
        <el-table-column prop="fee1" :label="deliveryCostName" />
        <el-table-column prop="fee2" label="上楼费" />
        <el-table-column prop="tip" label="服务费" />
        <el-table-column prop="receivable" label="总金额">
          <template slot-scope="scope">
            <span>{{ goodsPrice(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <i
              class="el-icon-delete"
              style="color: red; cursor: pointer;"
              @click="goodsDelete(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table> -->
      <lb-table
        ref="lbTable"
        class="tableOrder"
        :summary-method="getSummaries"
        show-summary
        highlight-current-row
        max-height="400"
        element-loading-text="加载中"
        :column="tableData.column"
        :data="commodityData"
        :pagination="false"
      />
      <el-form-item label="补充说明：" prop="description" class="label-block">
        <el-checkbox-group
          v-model="form.description"
          @change="descriptionChange"
        >
          <el-checkbox :label="4">用户已付款</el-checkbox>
          <el-checkbox :label="1">加急</el-checkbox>
          <el-checkbox :label="2">需发票</el-checkbox>
          <el-checkbox :label="3">自提</el-checkbox>
          <!-- <el-checkbox :label="4">月结</el-checkbox> -->
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="支付方式：" prop="paymentMethod" class="label-block">
        <el-radio-group v-model="form.paymentMethod" @change="paymentMethodChange">
          <el-radio v-for="(item,i) in paymentMethodList" :key="i" :label="item.label">{{ item.name }}</el-radio>
          <!-- <el-radio v-if="cinfo.settlementType === 2 && cinfo.monthlyUseOrgId === temp.orgId" :label="16">月结（{{ ((cinfo.settlementUseMonery || 0 ).toFixed(2)+'/'+ (cinfo.decimalSpare2 || 0 ).toFixed(2)) }}）</el-radio>
          <el-radio v-if="cinfo.cardCode && cinfo.cardUseOrgId === temp.orgId" :label="256">预付卡（{{ ((cinfo.cardSurplus || 0 )/100).toFixed(2) }}）</el-radio>
          <template v-else-if="(cinfo.settlementType === 2 && cinfo.monthlyUseOrgId !== temp.orgId) || (cinfo.cardCode && cinfo.cardUseOrgId !== temp.orgId)">
            <el-radio :label="1">现金2{{ cinfo.monthlyUseOrgId !== temp.orgId }}</el-radio>
          </template>
          <template v-if="cinfo.settlementType !== 2 && !cinfo.cardCode">
            <el-radio :label="1">现金1</el-radio>
          </template> -->
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="(appointmentInfo.sp1>>4 & 0x01)===1" label="预约时间：">
        <div class="appointment">
          <div class="appointment-row">
            <p class="timeContent" @click="showAppointment">
              <span v-if="!currentDayContent" class="placeholder">请选择预约时间</span>
              <span v-else>{{ currentDayContent }}</span>
            </p>
          </div>
          <el-card v-if="popoverVisible" class="appointment-warp">
            <h4>请选择预约时间</h4>
            <div class="left">
              <div class="head">
                <i v-show="appointmentList&&appointmentList.length>1" class="el-icon-arrow-left" @click="forward" />
                <div v-for="(item,index) in currentAppointment" :key="index" :class="currentDayInfo.day===item?'appointment-select':''" @click="selectAppointment(item, index)">
                  <span v-if="index===0">今天</span>
                  <span v-if="index===1">明天</span>
                  <span v-if="index===2">后天</span>
                  <span>{{ item }}</span>
                </div>
                <i v-show="appointmentList&&appointmentList.length>1" class="el-icon-arrow-right" @click="future" />
              </div>
              <div v-loading="$loadingPlugin.gettimeList" class="content">
                <div v-for="(item, idx) in timePartList.appointmentTimeList" :key="idx" class="content-item" @click="selectTimePart(item,idx)">
                  <div class="time-item">
                    <p v-if="item.dateFlag&&item.dateFlag===1" class="time-count">
                      <span :class="item.select?'time-active':''">{{ item.endTime }}前送达</span>
                    </p>
                    <p v-else class="time-count" :class="item.isFull?'p-disabel-gray':''">
                      <span :class="item.select?'time-active':''">{{ item.startTime+'~'+item.endTime }}</span><span v-if="item.isFull" class="dis">已约满</span><span v-if="(!item.isFull) && item.leftCount" class="count-left">{{ '(余' + item.leftCount + ')' }}</span>
                    </p>
                    <!-- <p :class="item.isFull?'p-disabel-gray':''" @click="selectTimePart(item,idx)">
                    <span :class="item.select?'time-active':''">{{ item.showIndex===0?currentAppointmentIndex===0?'今日送达':currentAppointmentIndex===1?'明日送达':currentAppointmentIndex===2?'后日送达':'':item.startTime+'~'+item.endTime }}</span><span v-if="item.isFull" class="dis">已约满</span><span v-if="!item.isFull && item.leftCount" class="left">{{ '(余' + item.leftCount + ')' }}</span>
                  </p> -->
                    <!-- <p>
                    <span>{{ item.startTime }}~{{ item.endTime }}</span><span v-if="false" class="dis">已约满</span>
                  </p> -->
                    <!-- <p class="p-disabel-gray">
                    <span>{{ item.startTime }}~{{ item.endTime }}</span><span v-if="item.isFull" class="dis">已约满</span>
                  </p> -->
                    <p v-if="item.select&&!item.isFull" :class="item.isFull?'p-disabel-gray':item.select?'time-active':''"> ✔ </p>
                  </div>
                </div>
                <p v-if="timePartList.appointmentTimeList.length===0" class="noAppointmentList">暂无可选时间段</p>
              </div>
            </div>
            <div class="foot">
              <el-button size="mini" @click="popoverVisible = false">取 消</el-button>
              <el-button size="mini" type="primary" @click="confirmed">确 定</el-button>
            </div>
          </el-card>
        </div>
      </el-form-item>

      <div class="footer">
        <el-form-item label="备注：">
          <el-input
            v-model="form.remark"
            style="width: 410px;"
            type="textarea"
            :rows="2"
            maxlength="30"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="$loadingPlugin.doSubmit || $loadingPlugin.sumitOrderFn"
            type="primary"
            class="submitBtn"
            @click="onSubmit"
          >提 交</el-button>
        </el-form-item>
      </div>
    </el-form>
  </el-card>
</template>

<script>
  import { parseTime } from '@/utils'
  import { accAdd } from '@/utils/math'
  import moment from 'dayjs'
  import { mapGetters } from 'vuex'
  import { accountopeningQuery, orderAppointment, findGoodsList, recheckbillCheck, depositinfoCheck, phoneOrderDefineprice, phoneOrderOtherPrice, findGoodTypeList, phoneOrderCsmCard, phoneOrderSubmit, phoneOrderUpdate, feeQueryByGood, phoneOrderAreaprice, phoneOrderSearchspecialPrice, queryDriverPrice } from '@/api'
  export default {
    name: 'place-an-order',
    props: {
      clientSelected: {
        type: Object,
        default: () => { return {} }
      },
      temp: {
        type: Object,
        default: () => { return {} }
      },
      shippingInfoSelected: {
        type: Object,
        default: () => { return {} }
      },
      oldAddress: {
        type: Array,
        default: []
      },
      oldPhoneList: {
        type: Array,
        default: []
      },
      currentuserInfo: {
        type: Object,
        default: () => { return {} }
      },
      purchaseHistory: {
        type: Array,
        default: []
      },
      shopList: {
        type: Array,
        default: []
      },
      currentPhoneData: {
        type: Object,
        default: () => { return {} }
      },
      depositOrderData: {
        type: Array,
        default: []
      },
      lastOrderDetail: {
        type: Object,
        default: () => { return {} }
      },
      mainGoodsPrices: {
        type: Array,
        default: []
      },
      floorfeeList: {
        type: Array,
        default: []
      },
      servePriceList: {
        type: Array,
        default: []
      },
      oldCustomInfo: {
        type: Object,
        default: () => { return {} }
      },
      appointmentInfo: {
        type: Object,
        default: () => { return {} }
      },
      depositDetailsInfo: {
        type: Object,
        default: () => { return {} }
      }
    },
    data() {
      return {
        form: {
          gtId: '',
          goodsId: '',
          specCode: '',
          description: [],
          remark: '',
          paymentMethod: null
        },
        goodTypeList: [],
        goodsList: [],
        commodityData: [],
        isOnSubmit: false,
        commodityIspickup: 0,
        prepaidCardInfo: {
          cardSurplus: 0
        },
        deliveryCostName: '远距配送费',
        canUseMonthly: false,
        preferentialPriceZero: false,
        isBasePrice: 0,
        readOnly: false,
        ainGoodsPrices: [], // 主营商品价格
        AreapriceList: [], // 区域价格
        list: [],
        cinfo: {},
        popoverVisible: false,
        showClear: false,
        currentDayContent: '',
        appointmentList: [],
        currentAppointment: [],
        currentAppointmentIndex: 0,
        currentDayInfo: {},
        timePartList: [],
        confirmedDayInfo: {},
        paymentMethodList: [],
        tableData: {
          column: [
            {
              prop: 'goodsName', label: '商品名称', align: 'center'
            },
            {
              prop: 'gprinceNum', label: '市价', align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  { (this.corpSettingData.sp5 >> 16 & 0x01) && row._edit && !row.definePrice ? (
                    <el-input class='EditInp' size='mini' value={row[column.property] } style='width: 80px' onBlur={(val) => { this.blurInput(row, column, val) }} onInput={(val) => { this.changeInput(row, column, val) }}> </el-input>
                  ) : (<span style={`textDecoration:${row.definePrice ? 'line-through;color:red' : ''}`}>{row[column.property] ? (row[column.property] * 1).toFixed(2) : 0}</span>)}
                </div>
              )
              }
            },
            {
              prop: 'definePrice', label: '特价', align: 'center',
              // render: (h, { row, $index }) => <span>{row.definePrice ? row.definePrice : 0}</span>
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  { row._edit && row.definePrice ? (
                    <el-input class='EditInp' size='mini' value={row[column.property] } style='width: 80px' onBlur={(val) => { this.blurInput(row, column, val) }} onInput={(val) => { this.changeInput(row, column, val) }}> </el-input>
                  ) : (<span >{row[column.property] ? (row[column.property] * 1).toFixed(2) : 0}</span>)}
                </div>
              )
              }
            },
            {
              prop: 'gcount', label: '数量', align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-input class='EditInp' maxlength='5' size='mini' value={row[column.property] } style='width: 80px' onBlur={(val) => { this.gcountblurInput(row, column, val) }} onInput={(val) => { this.changeInput(row, column, val) }}> </el-input>
                  ) : (<span >{row[column.property] ? (row[column.property] * 1) : ''}</span>)}
                </div>
              )
              }
            },
            {
              prop: 'gprefPrice', label: '优惠', align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {(this.corpSettingData.sp5 >> 24 & 0x01) && row._edit ? (
                    <el-input class='EditInp' size='mini' value={row[column.property] } style='width: 80px' onBlur={(val) => { this.blurInput(row, column, val) }} onInput={(val) => { this.changeInput(row, column, val) }}> </el-input>
                  ) : (<span >{row[column.property] ? (row[column.property] * 1).toFixed(2) : 0}</span>)}
                </div>
              )
              }
            },
            {
              prop: 'deliveryType', label: '优惠类型', align: 'center',
              render: (h, { row }) => { return (row.deliveryType ? <span >{row.deliveryType === 1 ? '大车用户' : '电子围栏用户'}</span> : '') }
            },
            {
              prop: 'fee1', label: '配送费', align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  { (this.corpSettingData.sp5 >> 18 & 0x01) && row._edit ? (
                    <el-input class='EditInp' maxlength='5' size='mini' value={row[column.property] } style='width: 80px' onBlur={(val) => { this.blurInput(row, column, val) }} onInput={(val) => { this.changeInput(row, column, val) }}> </el-input>
                  ) : (<span >{row[column.property] ? (row[column.property] * 1).toFixed(2) : 0.00}</span>)}
                </div>
              )
              }
            },
            {
              prop: 'fee2', label: '上楼费', align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  { (this.corpSettingData.sp5 >> 20 & 0x01) && row._edit ? (
                    <el-input class='EditInp' maxlength='5' size='mini' value={row[column.property] } style='width: 80px' onBlur={(val) => { this.blurInput(row, column, val) }} onInput={(val) => { this.changeInput(row, column, val) }}> </el-input>
                  ) : (<span >{row[column.property] ? (row[column.property] * 1).toFixed(2) : 0.00}</span>)}
                </div>
              )
              }
            },
            {
              prop: 'tip', label: '服务费', align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  { (this.corpSettingData.sp5 >> 22 & 0x01) && row._edit ? (
                    <el-input class='EditInp' maxlength='5' size='mini' value={row[column.property] } style='width: 80px' onBlur={(val) => { this.blurInput(row, column, val) }} onInput={(val) => { this.changeInput(row, column, val) }}> </el-input>
                  ) : (<span >{row[column.property] ? (row[column.property] * 1).toFixed(2) : 0.00}</span>)}
                </div>
              )
              }
            // render: (h, { row }) => <el-link onClick={() => this.openDetail(row)}>{row.orderCode}</el-link>
            },
            {
              prop: 'receivable', label: '总金额', align: 'center',
              render: (h, { row }) => <span >{this.goodsPrice(row)}</span>
            },
            {
              prop: '', label: '', align: 'center',
              // render: (h, { row, $index }) => <span onClick={() => this.delGoods($index) }><i class='el-icon-close' style='color: red;' /></span>
              render: (h, { row, $index }) => {
                return (!this.isFirstDepositOrder
                  ? <div>
                    <el-link size='mini' underline={false} onClick={() => this.handleEdit(row)}>
                      {row._edit ? '' : '编辑'}
                    </el-link>
                    <el-link size='mini' underline={false} onClick={() => this.handleSave(row) } >
                      {row._edit ? '保存' : ''}
                    </el-link>
                    <el-link size='mini' underline={false} onClick={() => this.goodsDelete(row)}>
                      删除
                    </el-link>

                  </div> : ''
                )
              }
            }
          ]
        },
        HuiZhiFlag: false // 回执的开关
      }
    },
    computed: {
      ...mapGetters([
        'orgList',
        'corpSettingData'
      ]),
      isFirstDepositOrder() {
        return this.depositDetailsInfo.depositDetails ? !!this.depositDetailsInfo.depositDetails.length : false
      },
      depositDetails() {
        return this.depositDetailsInfo.depositDetails || []
      }
    },
    watch: {
      commodityData(newVal, oldVal) {
        let preferentialPriceZero = false
        newVal.forEach((item) => {
          if (item.preferentialPrice2 === 0) {
            preferentialPriceZero = true
          }
        })
        this.preferentialPriceZero = preferentialPriceZero
        this.checkPayMethod()
      },
      'temp.orgId': {
        handler(newVal, oldVal) {
          this.paymentMethodList = [{ label: 1, name: '现金' }]
          // 默认支付方式
          // if (this.cinfo.monthlyUseOrgId === this.temp.orgId && this.cinfo.defaultPaymentMethod === 16 && this.cinfo.settlementType === 2) {
          //   this.form.paymentMethod = 16
          //  } else if (this.cinfo.cardUseOrgId === this.temp.orgId && this.cinfo.defaultPaymentMethod === 256 && this.cinfo.cardCode) {
          //   this.form.paymentMethod = 256
          // } else if (this.cinfo.settlementType === 2 && this.cinfo.cardCode && this.cinfo.cardUseOrgId === this.temp.orgId && this.cinfo.monthlyUseOrgId === this.temp.orgId) {
          //   this.form.paymentMethod = this.cinfo.defaultPaymentMethod
          // } else {
          //  this.form.paymentMethod = null
          // }
          // 展示支付方式
          if (this.cinfo.settlementType === 2 && this.cinfo.monthlyUseOrgId === this.temp.orgId && this.cinfo.cardCode && this.cinfo.cardUseOrgId === this.temp.orgId) {
            this.paymentMethodList = [{ label: 16, name: `月结（${((this.cinfo.settlementUseMonery || 0).toFixed(2) + `/` + (this.cinfo.decimalSpare2 || 0).toFixed(2))}  ）` },
                                      { label: 256, name: `预付卡（${this.cinfo.isMainCard === 1 ? ((this.cinfo.cardSurplus || 0) / 100).toFixed(2) : `总可用金额:${((this.cinfo.mainCardSurplus + this.cinfo.deputyCardSurplus) / 100).toFixed(2)}  主卡:${(this.cinfo.mainCardSurplus / 100).toFixed(2)} 副卡:${(this.cinfo.deputyCardSurplus / 100).toFixed(2)}`}）` }]
            this.setPaymentMethod()
            return
          }

          if (this.cinfo.settlementType === 2 && this.cinfo.monthlyUseOrgId === this.temp.orgId) {
            this.paymentMethodList = [{ label: 16, name: `月结（${((this.cinfo.settlementUseMonery || 0).toFixed(2) + `/` + (this.cinfo.decimalSpare2 || 0).toFixed(2))}  ）` }]
            this.setPaymentMethod()
            return
          }
          if (this.cinfo.cardCode && this.cinfo.cardUseOrgId === this.temp.orgId) {
            this.paymentMethodList = [{ label: 256, name: `预付卡（${this.cinfo.isMainCard === 1 ? ((this.cinfo.cardSurplus || 0) / 100).toFixed(2) : `总可用金额:${((this.cinfo.mainCardSurplus + this.cinfo.deputyCardSurplus) / 100).toFixed(2)}  主卡:${(this.cinfo.mainCardSurplus / 100).toFixed(2)} 副卡:${(this.cinfo.deputyCardSurplus / 100).toFixed(2)}`}）` },
                                      { label: 1, name: '现金' }]
            this.setPaymentMethod()
            return
          }
          if (!this.cinfo.cardCode && this.cinfo.settlementType !== 2) {
            this.paymentMethodList = [{ label: 1, name: '现金' }]
          }
          if ((this.cinfo.settlementType === 2 && this.cinfo.monthlyUseOrgId !== this.temp.orgId) || (this.cinfo.cardCode && this.cinfo.cardUseOrgId !== this.temp.orgId)) {
            this.paymentMethodList = [{ label: 1, name: '现金' }]
          }
          this.setPaymentMethod()
        },
        deep: true,
        immediate: true
      },
      'temp': {
        handler(newVal, oldVal) {
          this.form.remark = newVal.monthlyBillTips2
        },
        deep: true,
        immediate: true
      },
      cinfo(newVal, oldVal) {
        console.log('newVal', newVal)
        console.log('oldVal', oldVal)
      }
    },
    mounted() {
      // 回执
      if (this.corpSettingData.sp2 >> 27 & 0x01) {
        this.HuiZhiFlag = true
        this.form.description.push(5)
      }
    },
    methods: {
      // 用于首次押金单下单列表自动展示
      async refreshGoodsTable() {
        this.commodityData = []
        const depositDetails = this.depositDetailsInfo.depositDetails || []
        for (let i = 0; i < depositDetails.length; i++) {
          const { goodsCount } = depositDetails[i]
          const matchedGoodsList = this.goodsList.filter(goodsItem => goodsItem.specCode === depositDetails[i].specCode)
          if (matchedGoodsList.length) {
            this.form.goodsId = matchedGoodsList[0].goodsId
            this.form.specCode = matchedGoodsList[0].specCode
            this.form.goodsName = matchedGoodsList[0].goodsName
            await this.onAdd(1)
            this.changeInput(this.commodityData[i], { property: 'gcount' }, goodsCount)
            this.gcountblurInput(this.commodityData[i])
          }
        }
      },
      // 支付方式 （1）如果支付方式只有一种，默认勾选；（2）有多种支付方式的话，默认不勾选
      setPaymentMethod() {
        if (this.paymentMethodList.length > 1) {
          this.form.paymentMethod = null
        }
        if (this.paymentMethodList.length === 1) {
          this.form.paymentMethod = this.paymentMethodList[0].label
        }
      },
      // 合计的方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计'
            return
          }
          if (index === 5) {
            sums[index] = ''
            return
          }
          if (index === columns.length - 1) {
            sums[index] = ''
            return
          }
          let values = []
          if (index === 1) {
            values = data.map(item => {
              if (item.definePrice) {
                return 0
              }
              return Number(item[column.property])
            })
          } else {
            values = data.map(item => Number(item[column.property]))
          }
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            // if (index === 1) {

            // }
            if (!isNaN(value)) {
              return accAdd(prev, curr)
            } else {
              return prev
            }
          }, 0)
          sums[index]
        })
        return sums
      },
      // 添加商品
      async onAdd(count) {
        if (!this.temp.latitude || !this.temp.longitude) {
          this.$message.warning('您的详细地址不正确，请重新选择或修改')
          return
        }
        if (this.commodityData.length >= 5) {
          this.$message.warning('最多下单5个不同类型的商品')
          return
        }
        if (!this.checkOrder()) {
          return
        }
        this.feeval = 0
        this.distance = 0
        const param = {
          feejson: {
            orgid: this.temp.orgId,
            csmAddressId: this.shippingInfoSelected.csmAddressId,
            goodid: this.form.goodsId,
            cmstype: this.clientSelected.csmType
          }
        }
        const res = await feeQueryByGood(param)
        if (res.data) {
          this.feeval = res.data.fee
          this.distance = this.distanceFormat(res.data.distance)
        }
        this.driverDisCount1 = undefined // 大车用户配送费折扣
        this.driverDisCount2 = undefined // 大车用户上楼费折扣
        this.driverFee1 = undefined // 大车用户配送费
        this.driverFee2 = undefined // 大车用户上楼费
        this.deliveryType = 0
        if (this.distance) {
          const info = {
            distance: this.distanceFormat2(this.distance),
            goodsId: this.form.goodsId,
            csmType: this.clientSelected.csmType === 1 ? 1 : 2,
            csmId: this.clientSelected.csmId
          }
          const res = await queryDriverPrice(info)
          if (res.data) {
            this.driverDisCount1 = res.data.disCount1 // 大车用户配送费折扣
            this.driverDisCount2 = res.data.disCount2 // 大车用户上楼费折扣
            this.driverFee1 = res.data.fee1 // 大车用户配送费
            this.driverFee2 = res.data.fee2 // 大车用户上楼费
            this.deliveryType = 1
          }
        }
        if (res.exc) {
          this.$message.warning(res.exc)
          return
        }
        await this.addGoods()
      },
      distanceFormat(v) {
        if (!Number(v)) {
          return ''
        }
        var msg = (Number(v) || 0).toFixed(2)
        return msg
      },
      distanceFormat2(v) {
        if (!Number(v)) {
          return ''
        }
        var msg = (Number(v) / 1000 || 0).toFixed(2)
        return msg
      },
      // 获取预付卡
      async getOverage(val) {
        // console.log(this.cinfo)
        // console.log(val)
        if (this.cinfo.cardCount <= 0) {
          return
        }
        this.prepaidCardInfo = {}
        const params = {
          // corpSN: val.corpSN,
          csmCode: val.csmCode
        }
        const res = await phoneOrderCsmCard(params)
        if (res && res.data) {
          this.prepaidCardInfo = res.data
          this.checkPayMethod()
        } else {
          this.prepaidCardInfo = {}
        }
      },
      checkPayMethod() {
        // this.form.paymentMethod = ''
        // if ((this.prepaidCardInfo.csmCardStatus === 1 && this.prepaidCardInfo.settlementType === 2) || this.prepaidCardInfo.csmCardStatus !== 1) {
        //   this.form.paymentMethod = this.prepaidCardInfo.defaultPaymentMethod
        // }
        // if (this.prepaidCardInfo.settlementType === 2 && this.prepaidCardInfo.csmCardStatus !== 1 && !this.preferentialPriceZero) {
        //   this.form.paymentMethod = 16
        // }
        // if (this.prepaidCardInfo.settlementType === 1 && this.prepaidCardInfo.csmCardStatus === 1 && !this.preferentialPriceZero) {
        //   this.form.paymentMethod = 256
        // }
        // if ((this.prepaidCardInfo.settlementType === 1 && this.prepaidCardInfo.csmCardStatus !== 1 && !this.prepaidCardInfo.defaultPaymentMethod) || this.preferentialPriceZero) {
        //   this.form.paymentMethod = 1
        // }
        // if (!this.form.paymentMethod || (this.form.paymentMethod !== 1 && this.form.paymentMethod !== 16 && this.form.paymentMethod !== 256)) {
        //   this.form.paymentMethod = 1
        // }
        this.checkMonthly()
      },
      // 验证
      checkOrder() {
        if (!this.temp.orgId) {
          this.$message.warning('请先选择责任机构')
          return false
        }
        if (!this.form.gtId) {
          this.$message.warning('请选择商品分类')
          return false
        } else if (!this.form.goodsId) {
          this.$message.warning('请选择商品')
          return false
        }
        return true
      },
      updateGoods(commodityData) {
        this.getCalculate(commodityData)
          .then(res => {})
          .catch(err => {
            console.log(err, '编辑失败--------')
            const isExistIndex = this.commodityData.findIndex(
              item => item.goodsId === this.form.goodsId
            )
            if (isExistIndex || isExistIndex === 0) {
              if (this.commodityData[isExistIndex].purchaseQuantity > 1) {
                this.commodityData[isExistIndex].purchaseQuantity--
              } else {
                this.commodityData.splice(isExistIndex, 1)
              }
            } else {
              this.commodityData = this.commodityData.filter(
                item => item.goodsId !== this.form.goodsId
              )
            }
          })
      },
      // 添加商品
      async addGoods() {
        // commodityData
        var goodsInfo, gtInfo
        goodsInfo = this.goodsList.find(l => l.goodsId === this.form.goodsId)
        gtInfo = this.goodTypeList.find(l => l.gtId === this.form.gtId)
        // 特价自定义或优惠套餐配送费不覆盖
        if (!goodsInfo.diff || goodsInfo.preferentialPrice2 >= 0) {
          goodsInfo.deliveryFun = this.feeval
        }
        var rowdatas = this.commodityData
        for (var i in rowdatas) {
          var item = rowdatas[i]
          if (item.goodsId === goodsInfo.goodsId) {
            if (item.gcount >= 99999) {
              this.readOnly = true
              return
            } else {
              this.readOnly = false
            }
            this.$message.warning('此商品已存在 数量累加  1 ')
            item.gcount++
            delete item.userFee1
            delete item.userFee2
            await this.calCost(item)
            this.commodityData = [...this.commodityData]
            return
          }
        }

        var customerType = this.temp.csmType
        var baseprice0 = goodsInfo['price0'] || 0
        var baseprice = goodsInfo[('price' + customerType)] || baseprice0
        if (this.isBasePrice) {
          baseprice = baseprice0
        }

        var gprefprice = 0

        var paramInfo = {
          goodsCode: goodsInfo.goodsCode,
          gtSNNo: gtInfo.gtSNNo,
          fromflag: 1,
          orgSNNo: '',
          customerType: customerType
        }

        if (!this.temp.orgSNNo) {
          const orgInfo = this.shopList.filter((item) => {
            return item.orgId === this.temp.orgId
          })
          if (orgInfo.length > 0) {
            this.temp.orgSNNo = orgInfo[0].orgSNNo
          }
        }
        paramInfo.orgSNNo = this.temp.orgSNNo

        gprefprice = this.calcSPrice(paramInfo)

        var rowdata = { id: new Date().getTime(),
                        goodsName: goodsInfo.goodsName,
                        goodsId: goodsInfo.goodsId,
                        gprinceNum: baseprice,
                        tag: parseInt(baseprice * 100),
                        definePrice: 0,
                        diff: 0,
                        gcount: 1,
                        gprefPrice: gprefprice,
                        tip: goodsInfo.tip || 0,
                        fee1: goodsInfo.deliveryFun || 0,
                        fee2: goodsInfo.floorFun || 0,
                        baseFloorFee: goodsInfo.baseFloorFee || 0,
                        treceivable: 0,
                        gtId: gtInfo.gtId,
                        gtFlag: gtInfo.gtFlag,
                        priceScore: goodsInfo.requiredScore || 0,
                        requiredScore: goodsInfo.requiredScore || 0,
                        pricingMode: goodsInfo.pricingMode || 1,
                        specCode: goodsInfo.specCode || '',
                        specName: goodsInfo.specName || '',
                        storeCount: goodsInfo.storeCount || 0,
                        isSpeicalPriceFloor: goodsInfo.isSpeicalPriceFloor,
                        preferentialPrice2: goodsInfo.preferentialPrice2
        }

        if (gtInfo.gtFlag < 3 && !goodsInfo.diff) { // && this.isBasePrice == false
          // TODO 寻址 区域特价
          // var datas = $dlh.cache.getAreaPriceCache()
          await this.GetAreaprice()
          if (this.AreapriceList) {
            var areaItem = this.sosoAreaPrice(this.AreapriceList, goodsInfo.goodsId)
            if (areaItem) {
              if (this.isBasePrice) {
                rowdata.gprinceNum = areaItem['price0']
              } else {
                rowdata.gprinceNum = areaItem['price' + customerType] || areaItem['price0']
              }
            }
          }
          // 服务费
          var serveItem = this.sosoServicePrice(this.servePriceList, goodsInfo.goodsId)
          if (serveItem) {
            var index = Math.log(customerType || 1) / Math.log(2)
            index++
            var fee1 = serveItem['spFee' + index] || serveItem['spFee0']
            if (fee1 & 0x01 > 0) {
              rowdata.fee1 = (fee1 >> 1) * 0.01
            }
            var fee2 = serveItem['lpFee' + index] || serveItem['lpFee0']
            if (fee2 & 0x01 > 0) {
              rowdata.fee2 = (fee2 >> 1) * 0.01
            }

            var tip = serveItem['tpFee' + index] || serveItem['tpFee0']
            if (tip & 0x01 > 0) {
              rowdata.tip = (tip >> 1) * 0.01
            }

            rowdata.fee1 = rowdata.fee1 && Number(rowdata.fee1).toFixed(2)
            rowdata.fee2 = rowdata.fee2 && Number(rowdata.fee2).toFixed(2)
            rowdata.tip = rowdata.tip && Number(rowdata.tip).toFixed(2)
          }
        }
        if (goodsInfo.preferentialPrice2 >= 0) {
          // 优惠套餐服务费
          var serveItemFavorable = this.sosoServicePrice(this.servePriceList, goodsInfo.goodsId)
          if (serveItemFavorable) {
            var idx = Math.log(customerType || 1) / Math.log(2)
            idx++
            var fee1Favorable = serveItemFavorable['spFee' + idx] || serveItemFavorable['spFee0']
            if (fee1Favorable & 0x01 > 0) {
              rowdata.fee1 = (fee1Favorable >> 1) * 0.01
            }
            var fee2Favorable = serveItemFavorable['lpFee' + idx] || serveItemFavorable['lpFee0']
            if (fee2Favorable & 0x01 > 0) {
              rowdata.fee2 = (fee2Favorable >> 1) * 0.01
            }

            var tipFavorable = serveItemFavorable['tpFee' + idx] || serveItemFavorable['tpFee0']
            if (tipFavorable & 0x01 > 0) {
              rowdata.tip = (tipFavorable >> 1) * 0.01
            }

            rowdata.fee1 = rowdata.fee1 && Number(rowdata.fee1).toFixed(2)
            rowdata.fee2 = rowdata.fee2 && Number(rowdata.fee2).toFixed(2)
            rowdata.tip = rowdata.tip && Number(rowdata.tip).toFixed(2)
          }
        }
        // 特价自定义上楼费不覆盖
        if (!goodsInfo.isSpeicalPriceFloor || goodsInfo.preferentialPrice2 >= 0) {
          var floorDatas = this.floorfeeList
          if (floorDatas) {
            var floorFee = this.sosoFloorFee(floorDatas, goodsInfo.goodsId, customerType)
            rowdata.fee2 = floorFee
          } else {
            rowdata.fee2 = 0
          }
        }
        var toDecimal = function(str, p) {
          if (/^(-?\d+)(\.\d+)?$/.test(str)) {
            return parseFloat(str).toFixed(p || 2) * 1
          }
          return 0
        }
        // 如果有大车用户配送费折扣
        if (this.deliveryType) {
          if (this.driverDisCount1) {
            rowdata.fee1 = this.driverDisCount1 * rowdata.fee1
          } else if (this.driverFee1) {
            rowdata.fee1 = this.driverFee1
          } else if (this.driverFee1 === 0 && this.driverDisCount1 === 0) {
            rowdata.fee1 = 0
          }
          // 如果有大车用户上楼费折扣
          if (this.driverDisCount2) {
            rowdata.fee2 = this.driverDisCount2 * rowdata.fee2
          } else if (this.driverFee2) {
            rowdata.fee2 = this.driverFee2
          } else if (this.driverFee1 === 0 && this.driverDisCount1 === 0) {
            rowdata.fee2 = 0
          }
          rowdata.deliveryType = this.deliveryType
        }

        rowdata.yf = rowdata.fee1 // 单个商品原始的配送费
        rowdata.fee21 = rowdata.fee2 // 单个商品原始的上楼费
        rowdata.tip1 = rowdata.tip // 单个商品原始的服务费
        // console.log('rowdata', rowdata)
        // return
        rowdata.intSpare3 = 0
        if (goodsInfo.diff) {
          var definePrice = goodsInfo.definePrice || 0
          if (goodsInfo.diff === 1) {
            definePrice = Math.max(0, baseprice0 - definePrice)
          }
          // if (goodsInfo.diff === 2) {
          //   definePrice = goodsInfo.preferentialPrice2
          // }
          rowdata.definePrice = toDecimal(definePrice, 2)
          rowdata.diff = goodsInfo.diff
          // TODO 增加特价标识
          rowdata.intSpare3 |= 1
        }

        rowdata.newDiff = false
        if (goodsInfo.preferentialPrice2 >= 0) {
          // TODO 优惠套餐生效,特价失效
          rowdata.intSpare3 = 0
          rowdata.definePrice = goodsInfo.preferentialPrice2
          rowdata.diff = 2
          rowdata.newDiff = true
        }
        rowdata = await this.calCost(rowdata)

        // 说明流程配置开关 - 下单商品关联客户气瓶库存勾选
        if ((this.corpSettingData.sp4 >> 9 & 0x01) > 0 && !this.lastOrderDetail) {
          // 判断当前添加商品是否存在租瓶任务单中
          var isExistDeposit = false
          var depositOrderRows = this.depositOrderData
          if (depositOrderRows && depositOrderRows.length > 0) {
            for (var x = 0; x < depositOrderRows.length; x++) {
              if (depositOrderRows[x].specCode === rowdata.specCode) {
                isExistDeposit = true
                break
              }
            }
          }
          if (!isExistDeposit) {
            this.$confirm('客户未租用该瓶型,是否继续添加商品?', '提示', {
              confirmButtonText: '添加',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.commodityData.push(rowdata)
              // 按单位计价的，自动勾选“需回执”
              if (goodsInfo.pricingMode === 2) {
                // this.form.description.push(5)
              }
            }).catch((e) => {
            })
          } else {
            this.commodityData.push(rowdata)
            // 按单位计价的，自动勾选“需回执”
            if (goodsInfo.pricingMode === 2) {
              // this.form.description.push(5)
            }
          }
        } else {
          this.commodityData.push(rowdata)
          // 按单位计价的，自动勾选“需回执”
          if (goodsInfo.pricingMode === 2) {
            // this.form.description.push(5)
          }
        }
        this.btnStatus = true
        setTimeout(() => {
          this.btnStatus = false
        }, 1000)
      },
      calCost(rowdata) {
        if (!rowdata) { return }
        var toFloat = function(str) {
          if ((/^(-?\d+)(\.\d+)?$/).test(str)) {
            return parseFloat(str)
          }
          return 0
        }
        var toInt = function(str) {
          if ((/^-?\d+$/).test(str)) {
            return parseInt(str)
          }
          return 0
        }
        var toDecimal = function(str, p) {
          if (/^(-?\d+)(\.\d+)?$/.test(str)) {
            return parseFloat(str).toFixed(p || 2) * 1
          }
          return 0
        }
        var price = toFloat(rowdata.diff ? rowdata.definePrice : rowdata.gprinceNum)
        var gprefPrice = toFloat(rowdata.gprefPrice)
        if (gprefPrice > price) {
          gprefPrice = price
        }
        var gcount = toInt(rowdata.gcount)
        var fee1 = 0; var fee2 = 0; var tip = 0
        if (this.form.description !== 3) {
          if (rowdata.userTip) {
            tip = rowdata.userTip
          } else {
            tip = toFloat(rowdata.tip1) * gcount
          }
          if (rowdata.userFee1) {
            fee1 = rowdata.userFee1
          } else {
            fee1 = toFloat(rowdata.yf) * gcount
          }
          if (rowdata.userFee2) {
            fee2 = rowdata.userFee2
          } else {
            if (rowdata.isSpeicalPriceFloor && !rowdata.newDiff) {
              var floors = this.temp.floor || 1
              if (floors > 1) {
                if (this.maxFloor > 0) {
                  floors = Math.min(floors, this.maxFloor)
                }
                fee2 = ((floors - 1) * toFloat(rowdata.fee21))
                fee2 += rowdata.baseFloorFee
                fee2 *= gcount
              }
            } else {
              fee2 = rowdata.fee21 * gcount
            }
          }
        }
        rowdata.fee1 = toDecimal(fee1, 2).toFixed(2)
        rowdata.fee2 = toDecimal(fee2, 2).toFixed(2)

        rowdata.tip = toDecimal(tip, 2).toFixed(2)
        rowdata.gprefPrice = gprefPrice
        rowdata.treceivable = (parseFloat((price - gprefPrice) * gcount) + parseFloat(rowdata.tip * 1) + parseFloat(rowdata.fee1) + parseFloat(rowdata.fee2 * 1)).toFixed(2)
        return rowdata
      },
      sosoFloorFee(datas, gdId, csmType) {
        const floor = this.temp.floor ? this.temp.floor : 1
        const $ = {
          isEmptyObject: function(a) {
            var b
            for (b in a) { return !1 }
            return !0
          }
        }
        const isMatch = function(r, s) {
          return new RegExp(r).test(s)
        }
        var orgSNNo = this.temp.orgSNNo
        if (!this.temp.orgId) {
          orgSNNo = '001000000000000000000'
        }
        if (!this.temp.orgSNNo) {
          const orgInfo = this.shopList.filter((item) => {
            return item.orgId === this.temp.orgId
          })
          if (orgInfo.length > 0) {
            orgSNNo = orgInfo[0].orgSNNo
          }
        }

        var goods = false
        for (var i in datas) {
          var item = datas[i]
          if (item.goodsId === gdId) {
            goods = true
            break
          }
        }
        if (goods) {
          var matchArr = []
          for (i in datas) {
            item = datas[i]
            if (item.goodsId === gdId && isMatch('^' + item.orgPNNo, orgSNNo)) {
              matchArr.push(item)
            }
          }

          var length = 0
          var result = []
          for (var j in matchArr) {
            item = matchArr[j]
            if (item.orgPNNo.length > length) {
              length = item.orgPNNo.length
              result.length = 0
              result.push(item)
            } else if (item.orgPNNo.length === length) {
              result.push(item)
            }
          }
          var match = {}
          matchArr = []
          for (var k in result) {
            item = result[k]
            if (item.floorStart <= floor && item.floorEnd >= floor && item[('floorFee' + csmType)] >= 0) {
              matchArr.push(item)
            }
          }
          match = this.matchFloor(matchArr, floor)
          var arr = []
          if ($.isEmptyObject(match)) {
            for (i = 0; i < result.length; i++) {
              item = result[i]
              if (!(item.floorStart <= floor && item.floorEnd >= floor) && item[('floorFee' + csmType)] >= 0) {
                arr.push(item)
              }
            }
            match = this.matchFloor(arr, floor)
          }

          if ($.isEmptyObject(match)) {
            for (k in result) {
              item = result[k]
              if (item.floorStart <= floor && item.floorEnd >= floor && item['baseFee'] >= 0) {
                matchArr.push(item)
              }
            }
            match = this.matchFloor(matchArr, floor)
          }
          if ($.isEmptyObject(match)) {
            for (i = 0; i < result.length; i++) {
              item = result[i]
              if (!(item.floorStart <= floor && item.floorEnd >= floor) && item['baseFee'] >= 0) {
                arr.push(item)
              }
            }
            match = this.matchFloor(arr, floor)
          }
          var base = 0
          if (match[('floorFee' + csmType)] >= 0) {
            base = match[('floorFee' + csmType)]
          } else {
            base = (match.baseFee === undefined ? 0 : match.baseFee)
          }

          if (match.mode === 1) {
            return Number(base + (match.floor - match.floorStart) * match.modeAmount).toFixed(2)
          } else if (match.mode === 2) {
            result = Number(base - (match.floor - match.floorStart) * match.modeAmount).toFixed(2)
            return result < 0 ? 0 : result
          } else {
            return Number(base).toFixed(2)
          }
        }
        return undefined
      },
      matchFloor(arr, floor) {
        var match = {}
        for (var k in arr) {
          var item = arr[k]
          if (item.floorStart <= floor && floor <= item.floorEnd) {
            match = item
            match.floor = floor
            return match
          }
        }

        var max = 0
        for (k in arr) {
          item = arr[k]
          if (item.floorEnd < floor) {
            max++
          }
          if (max === arr.length) {
            match = arr[arr.length - 1]
            match.floor = match.floorEnd
            return match
          }
        }
        var min = 0
        for (k in arr) {
          item = arr[k]
          if (item.floorStart > floor) {
            min++
          }
          if (min === arr.length) {
            match = arr[0]
            match.floor = match.floorStart
            return match
          }
        }

        for (k in arr) {
          item = arr[k]
          if (item.floorStart > floor) {
            match = arr[k - 1]
            match.floor = match.floorEnd
            return match
          }
        }
        return match
      },
      sosoServicePrice(datas, gdId) {
        // TODO
        var orgSNNo = this.temp.orgSNNo
        if (!this.temp.orgId) {
          orgSNNo = '001000000000000000000'
        }
        if (!this.temp.orgSNNo) {
          const orgInfo = this.shopList.filter((item) => {
            return item.orgId === this.temp.orgId
          })
          if (orgInfo.length > 0) {
            orgSNNo = orgInfo[0].orgSNNo
          }
        }

        var flag = false
        for (var i in datas) {
          var item = datas[i]
          if (item.goodsId !== gdId) {
            if (flag) {
              break
            }
            continue
          } else if (flag === false) {
            flag = true
          }
          if (new RegExp('^' + item.orgPNNo).test(orgSNNo)) {
            return item
          }
        }
        return undefined
      },
      /* 优惠价 寻key 函数*/
      sosoFn(rg) {
        var cachekeys = this.cacheSPrice
        for (var key in cachekeys) { if (new RegExp(rg).test(key)) { return key } }
        return undefined
      },
      sosoAreaPrice(datas, gdId) {
        // TODO
        if (!this.temp.orgId) {
          return undefined
        }
        let orgSNNo = ''
        const orgInfo = this.shopList.filter((item) => {
          return item.orgId === this.temp.orgId
        })
        if (orgInfo.length > 0) {
          orgSNNo = orgInfo[0].orgSNNo
        }

        var flag = false
        for (var i in datas) {
          var item = datas[i]
          if (item.goodsId !== gdId) {
            if (flag) {
              break
            }
            continue
          } else if (flag === false) {
            flag = true
          }
          if (new RegExp('^' + item.orgPNNo).test(orgSNNo)) {
            // TODO 跋的千山万水,原来伊人在这里
            return item
          }
        }
        /** 回望遥遥路途,伊人在哪里**/
        return undefined
      },
      /* 优惠价格 寻址 */
      calcSPrice(info) {
        var cachekeys = this.cacheSPrice

        if (!cachekeys || cachekeys.length === 0) { return 0 }

        var goodsCode = info.goodsCode
        var gtSNNo = this.trimEnd('0', info.gtSNNo)
        var fromflag = info.fromflag
        var customerType = info.customerType
        var orgSNNo = (!info.orgSNNo ? '001' : info.orgSNNo)
        var tempkey = '^' + goodsCode + '-'
        var b = this.sosoFn(tempkey)
        if (!b) {
          tempkey = '^' + gtSNNo + '-'
        }
        if (!b && !this.sosoFn(tempkey)) { return 0 }

        if (fromflag !== '@' && !this.sosoFn(tempkey + fromflag + '-')) {
          fromflag = '@'
        }
        tempkey += fromflag + '-'
        if (!b && !this.sosoFn(tempkey)) { return 0 } else { b = true }

        while (orgSNNo.length >= 3) {
          b = this.sosoFn(tempkey + orgSNNo + '-')
          if (b) {
            break
          }

          orgSNNo = orgSNNo.substring(0, orgSNNo.length - 3)
        }
        if (orgSNNo.length === 0) {
          orgSNNo = '@'; b = false
        }
        tempkey += orgSNNo + '-'
        if (!b && !this.sosoFn(tempkey)) {
          if (fromflag !== '@') {
            info.fromflag = '@'
            return this.calcSPrice(info)
          }
          return 0
        } else { b = true }

        if (!this.sosoFn(tempkey + customerType)) {
          customerType = '@'
        }
        tempkey += customerType
        b = this.sosoFn(tempkey)
        if (!b) { return 0 }
        return cachekeys[b]
      },

      // 查询区域价格
      async GetAreaprice(params) {
        try {
          const res = await phoneOrderAreaprice(params)
          this.AreapriceList = res.data
        } catch (e) {
          console.log(e)
        }
      },
      // 应收
      goodsPrice(row) {
        var toFloat = function(str) {
          if ((/^(-?\d+)(\.\d+)?$/).test(str)) {
            return parseFloat(str)
          }
          return 0
        }
        var price = toFloat(row.diff ? row.definePrice : row.gprinceNum)
        var value = (price * 1 - row.gprefPrice * 1) * row.gcount * 1 + row.fee1 * 1 + row.fee2 * 1 + row.tip * 1
        row.receivable = value.toFixed(2)
        return value.toFixed(2)
      },

      async getDefaultGoodsInfo() {
        this.form.gtId = ''
        this.form.goodsId = ''
        this.goodTypeList = []
        this.goodsList = []
        if (this.isFirstDepositOrder) {
          await this.getGoodTypeList()
          this.form.gtId = this.goodTypeList[0].gtId
          await this.getGoodsList()
          this.refreshGoodsTable()
        } else if (this.purchaseHistory.length > 0) {
          const detailList = this.purchaseHistory[0].detailList
          if (detailList && detailList.length > 0) {
            await this.getGoodTypeList()

            this.form.gtId = detailList[0].gtId || ''
            await this.getGoodsList()
            this.form.goodsId = detailList[0].goodsId || ''
            this.form.specCode = detailList[0].specCode || ''
            this.goodsList.forEach((item) => {
              if (item.goodsId === this.form.goods) {
                this.form.goodsName = item.goodsName
              }
            })
          } else {
            await this.getGoodTypeList()
            this.form.gtId = this.goodTypeList[0].gtId
            await this.getGoodsList()
            this.form.goodsId = this.goodsList[0].goodsId || ''
            this.form.specCode = this.goodsList[0].specCode || ''
            this.goodsList.forEach((item) => {
              if (item.goodsId === this.form.goods) {
                this.form.goodsName = item.goodsName
              }
            })
          }
        } else {
          await this.getGoodTypeList()
          this.form.gtId = this.goodTypeList[0].gtId
          await this.getGoodsList()
          this.form.goodsId = this.goodsList[0].goodsId || ''
          this.form.specCode = this.goodsList[0].specCode || ''
          this.goodsList.forEach((item) => {
            if (item.goodsId === this.form.goods) {
              this.form.goodsName = item.goodsName
            }
          })
        }
      },
      // 商品分类
      async getGoodTypeList() {
        if (this.clientSelected.corpCode) {
          const params = {
            corpCode: this.clientSelected.corpCode
          }
          const res = await findGoodTypeList(params)
          this.goodTypeList = res.data
        }
      },
      goodTypeChange() {
        this.form.goodsId = ''
        this.goodsList = []
        this.$emit('goodTypeChange', { gTypeId: this.form.gtId })
        this.getGoodsList()
      },
      // 商品列表
      async getGoodsList() {
        const orgItem = this.shopList.find(item => item.orgId === this.temp.orgId)
        const params = {
          corpCode: this.clientSelected.corpCode,
          csmType: this.clientSelected.csmType,
          orgId: this.temp.orgId,
          orgSNNo: orgItem ? orgItem.orgSNNo || '' : '',
          gTypeId: this.form.gtId
        }
        const res = await findGoodsList(params)
        this.goodsList = res.data
        // this.initGoodList()
        await this.queryGoods()
        this.goodsList = this.list
      },
      async queryGoods() {
        const vm = this
        var gtInfo = vm.goodTypeList.find(l => l.gtId === this.form.gtId)
        if (!gtInfo) {
          return ''
        }
        this.specialPrice(gtInfo.gtSNNo)
        const fn = async function(rlt) {
          if (!vm.temp.orgId) {
            return
          }
          const csmTypeScope = vm.clientSelected.csmType * 1
          for (let i = rlt.data.length - 1; i >= 0; i--) {
            const item = rlt.data[i]
            if (!item.saleMode || (item.saleMode && item.saleMode === 0)) {
              rlt.data.splice(i, 1)
              continue
            }
            if (!item.csmType || (item.csmType && item.csmType === 0)) {
              rlt.data.splice(i, 1)
              continue
            }
            if (item.csmType && ((csmTypeScope & item.csmType) === 0)) {
              rlt.data.splice(i, 1)
              continue
            }
            if (item.orgIds) {
              var arr = item.orgIds.split(',')
              var index = arr.indexOf(vm.temp.orgId + '')
              if (index < 0) {
                rlt.data.splice(i, 1)
              }
            }
          }
          if (!rlt.data || rlt.data.length === 0) {
            vm.goodsTypesDetailList = []
            vm.$set(vm.form, 'goodsId', '')
          }
          if (vm.lastOrderDetail) {
            // 使用一次即作废
            vm.lastOrderDetail = undefined
            // 查询租瓶的列表进行比较判断订购列表存在客户未租用的瓶型
            // 说明是获取上次订单商品;并且存在租瓶任务单详情
            if (vm.depositOrderData && vm.depositOrderData.length > 0) {
              // 存在订单商品不再租瓶中
              var depositOrderIsNotExist = true
              var gridRows = vm.commodityData
              if (gridRows.length > 0) {
                for (var x = 0; x < gridRows.length; x++) {
                  depositOrderIsNotExist = true
                  for (var y = 0; y < vm.depositOrderData.length; y++) {
                    if (gridRows[x].specCode === vm.depositOrderData[y].specCode) {
                      depositOrderIsNotExist = false
                      break
                    }
                  }
                  // 说明订单列表存在商品不再租瓶单中
                  if (depositOrderIsNotExist) {
                    break
                  }
                }
                // 流程配置勾选-下单商品关联客户气瓶库存
                if (depositOrderIsNotExist && (vm.corpSettingData.sp4 >> 9 & 0x01) > 0) {
                  vm.$alert('注意：订购列表存在客户未租用的瓶型 !', '提示', {
                    confirmButtonText: '确定'
                  })
                }
              }
            } else {
              // 流程配置勾选-下单商品关联客户气瓶库存
              if ((vm.corpSettingData.sp4 >> 9 & 0x01) > 0) {
                vm.$alert('注意：订购列表存在客户未租用的瓶型 !', '提示', {
                  confirmButtonText: '确定'
                })
              }
            }
          }
        }
        if (this.temp && (this.temp.isCustomPrice || this.shippingInfoSelected.preferentialPackageId > 0) && !this.isBasePrice) {
          if (!this.temp.orgId) {
            this.$message.warning('请选择客户所属机构!')
            return
          }
          if (!this.shippingInfoSelected || !this.shippingInfoSelected.csmAddressId) {
            return
          }

          const params = {
            gtId: this.form.gtId,
            csmId: this.clientSelected.csmId,
            csmType: this.temp.csmType,
            orgSNNo: this.temp.orgSNNo,
            isCallCenter: true,
            csmAddressId: this.shippingInfoSelected.csmAddressId,
            fromPlat: 7
          }
          const res = await phoneOrderDefineprice(params)
          if (res.data) {
            this.list = res.data
            fn({ data: this.list })
          }
          return
        }
        if (gtInfo.gtFlag < 3 && this.mainGoodsPrices) {
          var cacheList = this.mainGoodsPrices
          this.list = []
          for (var i = 0; i < cacheList.length; i++) {
            var item = cacheList[i]
            if (item.gtId === gtInfo.gtId) {
              this.list.push(item)
            }
          }
          fn({ data: this.list })
          return
        }
        if (!this.clientSelected.csmId) {
          this.$message.warning('请先选择客户!')
          return
        }
        if (!this.temp.orgId) {
          this.$message.warning('请先选择客户所属机构!')
          return
        }
        const param = {
          gtId: this.form.gtId,
          orgSNNo: this.temp.orgSNNo,
          csmType: this.temp.csmType
        }
        const result = await phoneOrderOtherPrice(param)
        if (result.exc != null) { return }
        this.list = []
        this.list = result.data
        fn({ data: this.list })
      },
      async specialPrice(param) {
        if (this.cacheSPrice) {
          return
        }
        try {
          const rlt = await phoneOrderSearchspecialPrice({ gtSNNo: param })
          if (rlt.exc != null) { return }
          var list = rlt.data
          var cachekeys = {}
          for (var i = 0; i < list.length; i++) {
            var item = list[i]
            var snno = item.orgSNNo ? this.trimEnd('0', item.orgSNNo) : ''
            if (snno === '001' || !snno) { snno = '@' }
            var gtsnno = item.gtSNNo ? this.trimEnd('0', item.gtSNNo) : ''
            var key = `${item.goodsCode ? item.goodsCode : gtsnno}-${item.orderSource === 0 ? '@' : item.orderSource}-${snno}-${item.customerType === 0 ? '@' : item.customerType}`
            cachekeys[key] = item.price
          }

          this.cacheSPrice = cachekeys
        } catch (e) {
          console.log(e)
        }
      },
      trimEnd(c, str) {
        if (c == null || !c) {
          var rg = /s/
          var i = str.length
          while (rg.test(str.charAt(--i)));
          return str.slice(0, i + 1)
        } else {
          rg = new RegExp(c)
          i = str.length
          while (rg.test(str.charAt(--i)));
          return str.slice(0, i + 1)
        }
      },
      // 商品选择变化
      goodsChange(e) {
        const goodsSelect = this.goodsList.find(
          item => item.goodsId === this.form.goodsId
        )
        this.form.specCode = goodsSelect.specCode
        this.$emit('goodsChange', {
          goods: this.form.goodsId,
          specCode: this.form.specCode
        })
      },
      // 编辑订单
      changeInput(row, column, value) {
        row[column.property] = value
        this.$nextTick(() => {
          this.commodityData = [...this.commodityData]
        })
      },
      // 编辑校验
      blurInput(row, column, value) {
        var reg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/
        var flag = reg.test(row[column.property])
        if (!row[column.property]) {
          row[column.property] = 0
        }
        if (!flag && row[column.property]) {
          this.$message.warning(`${column.label}只能输入数字或小数，请重新输入`)
          row[column.property] = 0
        }
        switch (column.property) {
        case 'fee1':
          row.userFee1 = row[column.property]
          break
        case 'fee2':
          row.userFee2 = row[column.property]
          break
        case 'tip':
          row.userTip = row[column.property]
          break
        default:
          break
        }
      },
      // 数量改变
      gcountblurInput(row) {
        var reg = /^\+?[0-9]\d*$/
        var flag = reg.test(row.gcount)
        if (!row.gcount) {
          row.gcount = 0
        }
        if (!flag && row.gcount) {
          this.$message.warning(`只能输入数字，请重新输入`)
          row.gcount = 0
          return
        }
        if (row.gcount > 99999) {
          row.gcount = 99999
        }
        var toFloat = function(str) {
          if ((/^(-?\d+)(\.\d+)?$/).test(str)) {
            return parseFloat(str)
          }
          return 0
        }
        var rowdata = row
        var gconut = row.gcount
        if (rowdata.isSpeicalPriceFloor) {
          var floors = this.temp.floor || 1
          if (floors > 1) {
            if (this.maxFloor > 0) {
              floors = Math.min(floors, this.maxFloor)
            }
            rowdata.fee2 = ((floors - 1) * toFloat(rowdata.fee21))
            rowdata.fee2 += rowdata.baseFloorFee
            rowdata.fee2 *= rowdata.gcount
          }
        } else {
          row.fee21 === undefined ? row.fee21 = 0 : ''
          rowdata.fee2 = (gconut * row.fee21).toFixed(2)
        }
        rowdata.fee1 = (gconut * row.yf).toFixed(2)
        rowdata.tip = (gconut * row.tip1).toFixed(2)
        delete rowdata.userFee1
        delete rowdata.userFee2
        delete rowdata.userTip
        this.$nextTick(() => {
          this.commodityData = [...this.commodityData]
        })
      },
      // 编辑商品
      handleEdit(row, $index) {
        this.$set(row, '_edit', true)
        this.readOnly = false
      },
      // 保存商品
      handleSave(row, $index) {
        this.$set(row, '_edit', false)
        this.$set(this.commodityData, $index, JSON.parse(JSON.stringify(row)))
      },
      // 删除商品
      async goodsDelete(row) {
        this.commodityData = this.commodityData.filter(
          item => item.goodsId !== row.goodsId
        )
        // const commodityData = await this.handleCommodityData()
        // if (commodityData.length > 0) this.getCalculate(commodityData)
      },
      handleCommodityData() {
        const commodityData = this.commodityData.map(item => ({
          goodsId: item.goodsId,
          purchaseQuantity: item.purchaseQuantity,
          specCode: item.specCode,
          goodsName: item.goodsName
        }))
        return commodityData
      },
      async getCalculate(commodityData) {
        if (!commodityData.length > 0) return
        const params = await this.submitDataHandle()
        params.orderGoodsList = commodityData
        params.orderGoodsList.forEach((item) => {
          item.gtId = this.form.gtId
        })
        params.customerInfo.isCallCenter = true
        params.customerInfo.fromPlat = 7
        // const res = await phoneOrderCalculate(params)
        // if (res && res.data && res.data.orderGoodsList) {
        //  this.commodityData = res.data.orderGoodsList
        //  this.commodityIspickup = res.data.isPickUp
        //  this.deliveryCostName = `远距配送费（${(((res.data.distance / 1000).toFixed(2) || 0))}km）`
        //  const totalSalePrice = res.data.totalSalePrice
        //  const canUseVal = this.prepaidCardInfo.decimalSpare2 - this.prepaidCardInfo.settlementUseMonery
        //  if (canUseVal < totalSalePrice) {
        //    this.canUseMonthly = true
        //    if (this.prepaidCardInfo.settlementType === 2) {
        //     this.form.paymentMethod = null
        //    }
        //  } else {
        //    this.canUseMonthly = false
        //    this.checkPayMethod()
        //  }
        // }
        // return new Promise(async(resolve, reject) => {
        //   const params = await this.submitDataHandle()

        //   params.orderGoodsList = commodityData
        //   phoneOrderCalculate(params)
        //     .then(res => {
        //       if (res && res.data && res.data.orderGoodsList) {
        //         this.$set(this, 'commodityData', res.data.orderGoodsList)
        //       }
        //       resolve(res)
        //     })
        //     .catch(err => {
        //       reject(err)
        //     })
        // })
      },
      // 获取经纬度
      async getAddressUpdateStatus() {
        let oldAddress = this.oldAddress.find(
          item => item.csmAddressId === this.shippingInfoSelected.csmAddressId
        )
        const oldPhone = this.oldPhoneList.find(
          item => item.csmPhoneId === this.shippingInfoSelected.csmPhoneId
        )
        oldAddress = {
          ...oldAddress,
          ...oldPhone
        }

        const {
          contactName,
          telephone,
          address,
          province,
          city,
          area,
          floor,
          latitude,
          longitude,
          doorplate, isConfirm
        } = this.temp
        const newAddress = { contact: contactName, csmPhone: telephone, csmAddress: address, csmFloor: floor, latitude,
                             longitude, doorplate, isConfirm }
        newAddress.provinceCode = province
        newAddress.cityCode = city
        newAddress.countryCode = area

        console.log('newAddress:', newAddress, 'oldAddress:', oldAddress)
        if (newAddress && this.shippingInfoSelected.csmAddressId) {
          const flag = Object.keys(newAddress).some(
            item => newAddress[item] !== oldAddress[item]
          )
          const a = Object.keys(newAddress).find(item => newAddress[item] !== oldAddress[item])
          console.log('flag:' + flag + ',--------' + a)
          this.temp.updateStatus = flag ? 1 : 0
        } else {
          this.temp.updateStatus = 1
        }
      },

      descriptionChange(val) {
        if (((val.includes(3)) && this.commodityIspickup === 0) || ((val.includes(3)) && this.commodityIspickup === 1) || ((!val.includes(3)) && this.commodityIspickup === 1)) {
          let timer = null
          clearTimeout(timer)
          timer = setTimeout(() => {
            this.getCommodityData()
          }, 1000)
        }
        if (this.form.paymentMethod === 16) {
          if (this.form.description.indexOf(5) === -1) {
            this.form.description.push(5)
          }
        }
      },
      async getCommodityData() {
        const commodityData = await this.handleCommodityData()
        this.getCalculate(commodityData)
      },
      // 提交
      async onSubmit() {
        await this.$emit('validateForm')
      },
      async doSubmit() {
        if (!(this.clientSelected && this.clientSelected.csmCode)) {
          this.$message.error('请选择客户信息后操作')
        }
        if (this.clientSelected.csmStatus === 4) {
          this.$message.error('黑名单用户无法下单，请用户联系当地主管部门了解具体情况')
          return
        }
        if (!this.temp.province || !this.temp.city || !this.temp.area) {
          this.$message.error('请选择完整的所在区域')
          return
        }
        if (!this.temp.saveClient && (this.temp.contactName !== this.oldCustomInfo.contactName || this.temp.telephone !== this.oldCustomInfo.telephone || this.temp.province !== this.oldCustomInfo.province || this.temp.city !== this.oldCustomInfo.city || this.temp.area !== this.oldCustomInfo.area || this.temp.street !== this.oldCustomInfo.street || this.temp.address !== this.oldCustomInfo.address || this.temp.doorplate !== this.oldCustomInfo.doorplate || this.temp.floor !== this.oldCustomInfo.floor)) {
          this.$message.warning('请先保存客户')
          return
        }
        if (!this.commodityData.length > 0) {
          this.$message.error('请至少选择一件商品')
          return
        }
        if (this.canUseMonthly && this.form.paymentMethod === 16) {
          this.$message.error('用户余额不足，不可选择此支付方式')
          return
        }
        if (!this.form.paymentMethod) {
          this.$message.error('请选择支付方式')
          return
        }
        let cost = 0
        let numTrue = 0
        await this.commodityData.forEach(e => {
          cost += Number(e.receivable)
          if (!Number(e.gcount)) {
            numTrue++
          }
        })
        if (numTrue) {
          this.$message.error('商品数量不能为0')
          return
        }
        if (this.form.paymentMethod === 16 && (cost > (this.cinfo.decimalSpare2 - this.cinfo.settlementUseMonery))) {
          this.$message.error('月结额度不足')
          return
        }
        // if (this.form.paymentMethod === 256 && (cost > (this.cinfo.cardSurplus / 100))) {
        //   this.$message.error('预付卡额度不足')
        //   return
        // }
        const res = await recheckbillCheck({ csmid: this.clientSelected.csmId })
        if (res.data) {
          if (res.data > 0) {
            this.$message.error('该用户存在隐患尚未整改,请立即复检核查。目前无法购气')
            return
          }
        }
        var goodmsg = ''
        if (this.commodityData.length > 0) {
          for (let x = 0; x < this.commodityData.length; x++) {
            var specCode = this.commodityData[x].gcount + '###' + this.commodityData[x].specCode
            goodmsg = goodmsg + specCode + ','
          }
        }
        const param = {
          csmid: this.clientSelected.csmId,
          gooddesc: goodmsg,
          orgId: this.temp.orgId
        }
        const res2 = await depositinfoCheck(param)
        if (res2.data) {
          var str = res2.data.split('-')
          for (var x = 0; x < this.commodityData.length; x++) {
            if (this.commodityData[x].specCode === str[0]) {
              this.$message.error(this.commodityData[x].goodsName + str[1])
              return
            }
          }
        }
        this.submitDataHandle2()
      },
      async phoneOrderUpdate(r) {
        const params = {
          callCode: this.currentPhoneData.sn || '',
          phone: this.currentPhoneData.p5 || '',
          // corpSN: r.corpSN || '',
          taskCode: r.taskCode || ''
        }
        const res = await phoneOrderUpdate(params)
        console.log(res, '关联成功---')
      },
      getGoodsClear() {
        this.goodTypeList = []
        this.goodsList = []
        this.commodityData = []
        this.form.description = []
      },
      getRemarkClear() {
        // this.form.description = []
        this.form.remark = ''
      },
      async submitDataHandle() {
        const params = {
          orderGoodsList: this.commodityData,
          shop: {
            orgId: this.temp.orgId
          },
          customerInfo: this.clientSelected,
          address: {},
          distance: this.temp.distance,
          userInfo: this.currentuserInfo,
          isPickUp: this.form.description
            ? this.form.description.includes(3)
              ? 1
              : 0
            : '',
          isUrgent: this.form.description
            ? this.form.description.includes(1)
              ? 1
              : 0
            : '',
          isInvoice: this.form.description
            ? this.form.description.includes(2)
              ? 1
              : 0
            : '',
          paymentMethod: this.form.paymentMethod,
          reStatus: this.form.description
            ? this.form.description.includes(5)
              ? 2
              : 1
            : '',
          remark: this.form.remark,
          phone: this.temp.phone
        }
        await this.getAddressUpdateStatus()
        const {
          contactName,
          telephone,
          address,
          doorplate,
          province,
          provinceName,
          city,
          cityName,
          area,
          countryName,
          streetName,
          street,
          floor,
          updateStatus,
          latitude,
          longitude
        } = this.temp
        const addressData = {
          contactName,
          telephone,
          address,
          doorplate,
          provinceCode: province,
          provinceName,
          cityCode: city,
          cityName,
          countryCode: area,
          countryName,
          streetName,
          streetCode: street,
          floor,
          updateStatus,
          latitude,
          longitude
        }
        Object.keys(this.shippingInfoSelected).forEach(item => {
          if (!Object.keys(addressData).includes(item)) {
            addressData[item] = this.shippingInfoSelected[item]
          }
        })
        params.address = addressData
        params.address.idNumber = this.clientSelected.sfzh
        params.address.isConfirm = this.temp.isConfirm
        return params
      },
      async confirmAutoChargeback() {
        return new Promise((resolve, reject) => {
          if (this.corpSettingData.sp6 >> 25 & 0x01) {
            this.$confirm(`订单${this.corpSettingData.orderReturnDay}天未签收，自动退单，是否继续下单？`, '提示', {
              confirmButtonText: '立即下单',
              cancelButtonText: '暂不下单',
              type: 'warning'
            }).then(() => {
              resolve()
            }).catch(() => {
              reject()
            })
          } else {
            resolve()
          }
        })
      },
      async submitDataHandle2() {
        const orgInfo = this.shopList.filter((item) => {
          return item.orgId === this.temp.orgId
        })
        if (orgInfo.length > 0) {
          this.temp.orgName = orgInfo[0].orgName
        }
        // console.log('temp', this.temp)
        // console.log('shippingInfoSelected', this.shippingInfoSelected)
        const params = {
          'fromPlat': 7,
          'distance': this.distance,
          'csmId': this.clientSelected.csmId || '',
          'csmCode': this.clientSelected.csmCode || '',
          'csmName': this.clientSelected.csmName || '',
          'csmPhone': this.shippingInfoSelected.csmPhone || '',
          'contactPhone': this.shippingInfoSelected.csmPhone || '',
          'isPickUp': this.form.description.indexOf(3) > -1 ? 1 : 0,
          'contact': this.shippingInfoSelected.contact || '',
          'csmAddressId': this.shippingInfoSelected.csmAddressId || '',
          'csmAddress': `${this.temp.provinceName}${this.temp.cityName}${this.temp.countryName}${this.temp.streetName}${this.temp.address}${this.temp.doorplate}(楼层:${this.temp.floor ? this.temp.floor : 1})`,
          'intSpare5': this.shippingInfoSelected.csmFloor || 1, // 楼层
          'csmType': this.clientSelected.csmType || '',
          'strSpare2': this.temp.sfzh || '',
          'insureEndDt': this.temp.insurance ? this.temp.insurance[1] : '',
          'saleMan': this.temp.saleMan || '',
          'dateTimeSpare2': this.shippingInfoSelected.lastSCheckDt ? this.shippingInfoSelected.lastSCheckDt : '',
          'lon': this.temp.longitude.toFixed(6),
          'lat': this.temp.latitude.toFixed(6),
          'orgId': this.temp.orgId || '',
          'orgSNNo': this.temp.orgSNNo || '',
          'orgName': this.temp.orgName || '',
          'ownerId': this.currentuserInfo.userId || '',
          'ownerCode': this.currentuserInfo.userCode || '',
          'ownerName': this.currentuserInfo.userName || '',
          'isUrgent': this.form.description.indexOf(1) > -1 ? 1 : 0, // 加急
          'isInvoice': this.form.description.indexOf(2) > -1 ? 1 : 0, // 需发票
          'paymentMethod': this.form.paymentMethod,
          'reStatus': this.form.description.indexOf(5) > -1 ? 2 : 1, // 需回执
          'isPay': this.form.description.indexOf(4) > -1 ? 1 : 2, // 用户已付款
          // 'intSpare1': this.submitForm.checkList.isZb ? 1 : 0,
          'remark': this.form.remark,
          'bindDriverName': this.clientSelected.driverName,
          'orderFlag': 1
        }
        if (this.isFirstDepositOrder) {
          params.relatedDepositCode = this.depositDetailsInfo.depositCode
        }
        for (var value in params) {
          if (!params[value]) {
            delete params[value]
          }
        }
        if ((this.appointmentInfo.sp1 >> 4 & 0x01) === 1) {
          if (!this.currentDayContent) {
            this.$message.error('请选择预约时间')
            return
          } else {
            params.appointmentDt = new Date(this.confirmedDayInfo.day + ' ' + this.confirmedDayInfo.time.startTime)
            params.dateTimeSpare1 = new Date(this.confirmedDayInfo.day + ' ' + this.confirmedDayInfo.time.endTime)
          }
        }
        this.commodityData = this.commodityData.map(item => ({
          ...item,
          gprince: item.preferentialPrice2 && item.preferentialPrice2 >= 0 ? item.preferentialPrice2 : item.diff ? item.definePrice : item.gprinceNum
        }))
        await this.confirmAutoChargeback()
        this.sumitOrderFn(params, this.commodityData, false)
      },
      async sumitOrderFn(params, tables, keep) {
        const vm = this
        if (tables && tables.length > 0) {
          // console.log('params', params)
          const res = await phoneOrderSubmit({
            billJson: params,
            detailJson: tables,
            gasCheck: 0,
            callCode: ''
          })
          if (res.success) {
            vm.$message.success('订单提交成功')
            vm.commodityData = []
            vm.getTimeClear()
            if (!keep) {
              vm.getGoodsClear()
              vm.$emit('onSubmit')
            }
          }
        } else {
          vm.$message.warning('请添加商品')
        }
      },
      placeAnOrderClear() {
        this.form.gtId = ''
        this.form.goodsId = ''
        this.commodityData = []
        this.goodTypeList = []
        this.goodsList = []
        this.form.description = []
      },
      paymentMethodChange() {
        this.checkMonthly()
      },
      checkMonthly() {
        if (this.form.paymentMethod === 16) {
          if (this.form.description.indexOf(5) === -1) {
            this.form.description.push(5)
          }
        } else {
          // if (this.form.description.length > 0) {
          //   console.log(1111)
          //   this.form.description = this.form.description.filter(item => item !== 5)
          // }
        }
      },
      getTimeClear() {
        this.appointmentList = []
        // this.appointmentInfo = {}
        this.currentAppointment = []
        this.currentAppointmentIndex = 0
        this.currentDayInfo = {}
        this.confirmedDayInfo = {}
        this.timePartList = {}
        this.currentDayContent = ''
      },
      async showAppointment() {
        const { data } = await accountopeningQuery({ orgId: this.appointmentInfo.orgId })
        this.currentAppointment = []
        const date = moment(new Date())
        if (data.range === 0) {
          this.currentAppointment.push(parseTime(date.format(), '{y}-{m}-{d}'))
        } else if (data.range === 1) {
          this.currentAppointment.push(parseTime(date.format(), '{y}-{m}-{d}'), parseTime(date.add(1, 'days').format(), '{y}-{m}-{d}'))
        } else if (data.range === 2) {
          this.currentAppointment.push(parseTime(date.format(), '{y}-{m}-{d}'), parseTime(date.add(1, 'days').format(), '{y}-{m}-{d}'), parseTime(date.add(2, 'days').format(), '{y}-{m}-{d}'))
        }
        this.currentDayInfo.day = parseTime(new Date(), '{y}-{m}-{d}')
        await this.gettimeList()
        // this.getTimeClear()
        if (this.appointmentInfo && (this.appointmentInfo.sp1 >> 4 & 0x01) === 1) {
          this.appointmentHandle()
        }
        if (this.confirmedDayInfo && this.confirmedDayInfo.day) {
          this.currentDayInfo.day = this.confirmedDayInfo.day
          await this.gettimeList()
          const c_item = this.timePartList.appointmentTimeList.findIndex(item => item.startTime === this.confirmedDayInfo.time.startTime)
          if (c_item) {
            this.timePartList.appointmentTimeList[c_item].select = true
          } else {
            this.timePartList.appointmentTimeList[0].select = true
          }
          this.currentDayInfo.time = this.confirmedDayInfo.time
        }
        this.popoverVisible = !this.popoverVisible
      },
      clearAppointment() {
        this.popoverVisible = !this.popoverVisible
        this.showClear = false
      },
      async appointmentHandle() {
        // this.appointmentList = this.appointmentInfo.appointmentTimes ? splitArray(this.appointmentInfo.appointmentTimes, 3) : []
        if (this.appointmentList.length > 0) {
          this.currentAppointment = this.appointmentList[0]
        }
        this.currentAppointmentIndex = 0
        if (this.currentAppointment.length > 0) {
          this.currentDayInfo.day = this.currentAppointment[0]
          await this.gettimeList()
          if (this.timePartList.appointmentTimeList && this.timePartList.appointmentTimeList.length > 0) {
            for (let i = 0; i <= this.timePartList.appointmentTimeList.length; i++) {
              if (!(this.timePartList.appointmentTimeList[i] && this.timePartList.appointmentTimeList[i].isFull)) {
                this.timePartList.appointmentTimeList[i].select = true
                this.currentDayInfo.time = this.timePartList.appointmentTimeList[i]
                break
              }
            }
          } else {
            const tomorrow = this.currentAppointment[this.currentAppointmentIndex + 1]
            this.selectAppointment(tomorrow, this.currentAppointmentIndex + 1)
          }
        }
      },

      forward() {
        if (this.currentAppointmentIndex > 0) this.currentAppointmentIndex--
        this.currentAppointment = this.appointmentList[this.currentAppointmentIndex]
      },
      future() {
        if (this.currentAppointmentIndex < (this.appointmentList.length - 1)) this.currentAppointmentIndex++
        this.currentAppointment = this.appointmentList[this.currentAppointmentIndex]
      },
      // 选中天
      async selectAppointment(val, index) {
        this.currentAppointmentIndex = index
        this.currentDayInfo.day = val
        this.currentDayInfo.time = null
        this.timePartList.appointmentTimeList = []
        await this.gettimeList()
        if (this.timePartList.appointmentTimeList && this.timePartList.appointmentTimeList.length > 0) {
          for (let i = 0; i <= this.timePartList.appointmentTimeList.length; i++) {
            if (!(this.timePartList.appointmentTimeList[i] && this.timePartList.appointmentTimeList[i].isFull)) {
              if (this.timePartList.appointmentTimeList[i]) {
                this.timePartList.appointmentTimeList[i].select = true
                this.currentDayInfo.time = this.timePartList.appointmentTimeList[i]
              }
              break
            }
          }
        }
      },
      // 选中时间段
      selectTimePart(val, index) {
        if (val.isFull) {
          this.$message.warning('该时段已约满')
          return
        } else {
          const i = this.timePartList.appointmentTimeList.findIndex(item => item.select)
          if (i !== -1) {
            this.timePartList.appointmentTimeList[i].select = false
            this.timePartList.appointmentTimeList[index].select = true
            this.currentDayInfo.time = val
          }
        }
      },
      confirmed() {
        if (this.currentDayInfo.day && this.currentDayInfo.time) {
          this.currentDayContent = this.currentDayInfo.day + '  ' + this.currentDayInfo.time.startTime + '~' + this.currentDayInfo.time.endTime
          if (this.currentDayInfo.time.dateFlag === 1) {
            this.currentDayContent = this.currentDayInfo.day + '  ' + this.currentDayInfo.time.endTime + ' 前送达'
          }
          this.popoverVisible = false
          this.confirmedDayInfo = JSON.parse(JSON.stringify(this.currentDayInfo))
        } else {
          if (this.timePartList.appointmentTimeList.length === 0) {
            this.$message.warning('无可选时间段')
          } else {
            this.$message.warning('请选择时间段')
          }
        }
      },
      // 获取时间段
      async gettimeList() {
        if (!this.clientSelected || !this.clientSelected.csmId) {
          return
        }
        if (!this.temp || !this.temp.orgId) {
          return
        }
        const params = {
          customerInfo: this.clientSelected,
          date: this.currentDayInfo.day || parseTime(new Date(), '{y}-{m}-{d}'),
          orgId: this.temp.orgId,
          csmId: this.clientSelected.csmId
        }
        const res = await orderAppointment(params)
        if (res && res.data) {
          this.timePartList = res.data
          const that = this
          let appointmentTimeList = []
          if (res.data.appointmentTimeList && res.data.appointmentTimeList.length > 0) {
            appointmentTimeList = res.data.appointmentTimeList
          }
          that.timePartList.appointmentTimeList = appointmentTimeList
          if (appointmentTimeList.length > 0) {
            appointmentTimeList.forEach((item, index) => {
              that.commodityData.forEach((ele, orderI) => {
                item.appointmentList.forEach((e, idx) => {
                  if (e.goodsId === ele.goodsId) {
                    that.timePartList.appointmentTimeList[index].appointmentList[idx]['existAppointment'] = true
                  }
                  if (ele.goodsName.indexOf('15') > -1 && e.goodsId === ele.goodsId) {
                    item.idx = idx
                  }
                })
              })
            })

            that.timePartList.appointmentTimeList = that.timePartList.appointmentTimeList.map(item => ({
              ...item,
              select: false,
              leftCount: item.idx > -1 ? item.appointmentList[item.idx].leftCount : 0,
              isFull: item.appointmentList.some(item => item.existAppointment && item.status === 0)
            }))
            console.log(that.timePartList.appointmentTimeList, '-------------')
          }
        }
      },
      dateDiff(interval, dt1, dt2) {
        if (!dt1) {
          dt1 = new Date()
        }
        if (!dt2) {
          dt2 = new Date()
        }
        if (arguments.length < 2) {
          return 0
        }
        var objInterval = {
          'D': 1000 * 60 * 60 * 24,
          'H': 1000 * 60 * 60,
          'M': 1000 * 60,
          'S': 1000,
          'T': 1
        }
        interval = interval.toUpperCase()
        // return Math.round((dt2.getTime() - dt1.getTime()) / eval('objInterval.' + interval))
        return Math.round((dt2.getTime() - dt1.getTime()) / objInterval[interval])
      }
    }
  }
</script>

<style lang="scss" scoped>
.card {
  margin-left: 108px;
  overflow: visible;
  border-radius: 8px;
  & /deep/ .el-card__header {
    padding-bottom: 10px;
    padding-left: 10px;
    font-size: 14px;
    font-weight: bold;
  }
  & /deep/ .el-card__body {
    padding: 10px;
  }
  .goods-table {
    margin-bottom: 10px;
  }
  .label-block {
    display: block;
  }
  .footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.purchaseQuantity {
  width: 100%;
  & /deep/ .el-input {
    width: 100%;
  }
}
.submitBtn {
  width: 100px;
  height: 40px;
  font-size: 14px;
}
.line-throuht {
  color: #F56C6C;
  text-decoration: line-through;
}
.appointment {
  position: relative;
  width: 380px;
  cursor: pointer;
  .timeContent {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    border-bottom: 1px solid #dcdfe6;
    .placeholder {
      color: #c0c4cc;
    }
    img {
      width: 24px;
      height: 24px;
    }
  }
  .appointment-warp {
    position: absolute;
    bottom: 30px;
    z-index: 9999;
    width: 380px;
    transform: scale(0.9);
    h4 {
      margin: 0 0 8px 0;
      font-weight: 500;
      text-align: center;
      border-bottom: 1px solid #DCDFE6;
    }
    .left {
      display: flex;
      padding-bottom: 8px;
      border-bottom: 1px solid #DCDFE6;
    }
    .head {
      width: 100px;
      background-color: #d7d7d7;
      border-left: 1px solid #d7d7d7;
      div {
        padding: 10px 0;
        text-align: center;
        cursor: pointer;
        background-color: #d7d7d7;
        flex: 1;
        span {
          display: block;
          line-height: 20px;
        }
        &:hover {
          background: #EBEEF5;
        }
      }
      .appointment-select {
        color: $themeColor;
        background-color: white;
      }
      i {
        font-size: 24px;
      }
    }
    .content {
      flex: 1;
      min-height: 100px;
      .content-item {
        width: 100%;
        .time-item {
          display: flex;
          padding-left: 10px;
          &:hover {
            background: #EBEEF5;
          }
          p {
            min-width: 30px;
            text-align: center;
            cursor: pointer;
            span {
              display: block;
            }
            .dis {
              color: red;
            }
          }
          .time-count {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            width: 200px;
            span:nth-child(1) {
              margin-right: 20px;
            }
          }

          .p-disabel-gray {
            span:nth-child(1) {
              color: #c0c4cc;
            }
          }
          .time-active {
            color: $themeColor;
            // background-color: rgba(19, 177, 177, 0.2);
          }
        }
      }
      .noAppointmentList {
        min-height: 162px;
        line-height: 162px;
        color: #c0c4cc;
        text-align: center;
      }
    }
    .foot {
      margin-top: 8px;
      text-align: right;
    }
  }
}
</style>
